package com.beaven.beavenime.view.keyboard

import android.content.Context
import android.graphics.RectF
import com.beaven.beavenime.utils.getDefaultKeyboardHeight
import com.beaven.beavenime.utils.getDefaultKeyboardWidth

class KeyboardLayoutSet(context: Context) {

    companion object {
        @JvmStatic
        private val rowOneArray = arrayOf('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p')
        @JvmStatic
        private val rowTwoArray = arrayOf('a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l')
        @JvmStatic
        private val rowThreeArray = arrayOf('z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.')
    }

    private val keyboardDefaultWidth = getDefaultKeyboardWidth(context.resources)
    private val keyboardDefaultHeight = getDefaultKeyboardHeight(context.resources)


    fun buildLayoutSet(): List<KeyCode> {
        val keyWidth = keyCodeWidth(rowOneArray.size)
        val list = ArrayList<KeyCode>()
        for (i in rowOneArray.indices) {
            val paintX = getPaintX(i, keyWidth)
            val keyCode = KeyCode(
                rowOneArray[i].toInt(),
                keyWidth,
                60f,
                0,
                i,
                paintX,
                10f,
                getHitBox(paintX, keyWidth)
            )
            list.add(keyCode)
        }
        return list
    }

    private fun getHitBox(paintX: Float, keyWidth: Float): RectF {
        return RectF().also { rect ->
            rect.top = 5f
            rect.bottom = 200 + 5f
            rect.left = paintX - 2
            rect.right = paintX + keyWidth + 2
        }
    }

    private fun getPaintX(i: Int, keyWidth: Float): Float {
        return 4 * (i + 1) + keyWidth * i
    }

    /**
     * 4|code|2 2|code|2 2|code|4
     */
    private fun keyCodeWidth(size: Int): Float {
        val keyboardSizeSum = (keyboardDefaultWidth - (size + 1) * 4).toFloat()
        return keyboardSizeSum / size
    }

}